<?php
/* 
 * ebiz front
 * 
 * Customer Service
 * 
 * @author allen
 * 
 */

require_once '../app/core/services/BaseService.php';
require_once '../app/util/CommonUtil.php';
require_once '../app/models/UserDaoTest.php';
require_once '../app/models/ApplySchoolActingDao.php';
//require_once '../app/models/EmailDao.php';
require_once '../app/models/ConfigDao.php';
require_once '../app/constants/ConfigConstants.php';

class CustomerServiceTest extends BaseService 
{
	
	private $userDao;
	private $emailDao;
//	private $emailTemplateDao;
	private $configDao;
	/**
	 * Apply School Acting Model
	 *
	 * @var ApplySchoolActingDao
	 * @desc by M.Wang 2009-09-02 updated
	 */
	private $applySchoolActingDao;
	
	public function __construct(){
		parent::__construct();
        $this->userDao = new UserDaoTest($this->dbUtil);
        $this->emailDao = new EmailDao($this->dbUtil);
        $this->configDao = new ConfigDao($this->dbUtil);
//        $this->emailTemplateDao = new EmailTemplateDao($this->dbUtil);
        $this->applySchoolActingDao = new ApplySchoolActingDao( $this->dbUtil );
	}
    
    public function addUser($param){    //this is registert function
        $id = $this->userDao->saveUser($param);
        $currentTime = CommonUtil::getUniqueKey();
        $activate_key = base64_encode($id.'-'.$currentTime);
        $param = array($activate_key, $id);
        $this->userDao->updateActivateKey($param);
        return $activate_key;
    } 

    /**
     * Add campus agent
     *
     * @author by M.Wang
     * @param array $param
     * @return boolean
     */
    public function addAgent( $param ){
    	return $this->applySchoolActingDao->saveAgent( $param );
    }
    
    public function getByEmailAndPassword($param){      //this is login function
        $result = $this->userDao->getByEmailAndPassword($param);
    	if($result){ 
        	
            return 1; 	//login success
        }else{
        	return -1;  //do not have this person info or login error
        }
    }
    
    public function getCustomerInfoByEmailAndPassword($param){      //this is login function to get the customer id
        return $this->userDao->getByEmailAndPassword($param);
    }
    
    public function activeUser($userId){
        $this->userDao->updateModifiedTime($userId);
        
        $userInfo = $this->userDao->getUserById($userId);
        $name = $userInfo[0]["name"];
        $email = $userInfo[0]["email"];
        $activate_key = $userInfo[0]["activate_key"];
        
        $emailTitle = ACTIVEEMAILTITLE;
        $link = "<a href='"."http://".ConfigConstants::$domainPath."/u/activation?uid=".$activate_key."'>"."http://".ConfigConstants::$domainPath."/u/activation?uid=".$activate_key."</a>";
        $emailParam = array("name" => $name, "link" => $link, "email" => $email);
            
        $emailService = new EmailService();
        $emailTitle = ACTIVEEMAILTITLE;//邮件title
        $emailBodyToUser = $emailService->activeEmailView($emailParam);//获得邮件主体内容
        MailUtil::sendMail($email, $emailTitle, $emailBodyToUser);
    	
    }

    public function activation($id, $activate_key){     //this is activation user's activate_key status 
    	$avaliUser = $this->userDao->getActivateKey($activate_key);    //find the useable id and isdelete=0 and ststus=0
    	if(!empty($avaliUser) && $avaliUser[0]['id'] == $id){  //if id equal db's id
    		$result = $this->userDao->getByActivateKey($activate_key);    //find the user ,validata in the 24 hour 
    		if(!empty($result)){
    			$status = 1;
    			$param = array($status, $id);
    			$this->userDao->updateStatus($param);
    			//$this->userDao->deleteActivateKey($id);
    			return 1;    //this activate_key is right 
    		}else{
//    			$this->userDao->deleteUserById($id);
    			return 0;    //this activate_key is error or the time is overtime
    		}    		
    	}else{
    		return -1;    //this is invalidation user   		
    	}    	
    }
    
    public function validateEmail($email){  //this is validate Email if it exist in the database
        $result = $this->userDao->getByEmail($email);
        if(!empty($result)) { 
            return false;   //already exist
        }else{
            return true;    //do not have
        }
    }
    
    /**
     * 2009-09-02 Updated by M.Wang
     * 
     * @desc add param use for get user information
     * @param string $name
     * @return bool|array
     */
    public function validateUserName($name, $bool_getInfo = false ){  //this is validate username if it exist in the database
        $result = $this->userDao->getByName($name);
        if( !$bool_getInfo ){
	        if(!empty($result)) { 
	            return false;   //already exist
	        }else{
	            return true;    //do not have
	        }
        }else{
        	if( empty( $result ) )
        	   return $result;
        	return $result[0];
        }
    }
    
    public function getPassword($email){    //findback password
//        $result = $this->userDao->getByEmail($email);   //get result by email 
        $result = $this->userDao->getByEmailForPassword($email);   //get result by email 
        if(!empty($result)) {   //have the email
            $id =  $result[0]['id'];  //direct return of one-dimensional array
            $name = $result[0]['name'];
            $uniqueKey = CommonUtil::getUniqueKey();
            $getPasswordKey = base64_encode($id.'-'.$uniqueKey);
            $param = array($getPasswordKey, $id, $name);
            $this->userDao->updatePasswordKeyCreated($id);   //save the password_key_created time
//            $validataIdTime = $this->userDao->getByGetPasswordKey($getPasswordKey);
//            if(empty($validataIdTime)){    //if time>24H
//            	return false;
//            }else{   //time in 24H then can register
            	$this->userDao->updateGetPasswordKey($param);       //execut update   
                return $param;  //id will in the getPasswordKey 
//            }
        }else{  //do not have the email
            return false;
        }
    }   
    
    public function updatePassword($id, $getPasswordKey, $newPassword){
    	$result = $this->userDao->getByGetPasswordKey($getPasswordKey);
    	if(!empty($result) && $result[0]['id'] == $id){    //find the value and id is right
    		$param = array($newPassword, $id, $getPasswordKey);
            $this->userDao->updatePassword($param);     //update password if within 24H 
            $this->userDao->deleteGetPasswordKey($id);   
            return true;
    	}else{     //the value or id is error or timeout
    		return false;
    	}
    }
    
    public function updateLastLoginById($id){
    	$this->userDao->updateLastLoginById($id);
    }
    
    public function getCustomerById($id){
    	$result = array();
    	$result = $this->userDao->getCustomerById($id);
    	return $result;
    }
    
    public function getCustomerCampusesNameByCid($customerId){
    	$result = $this->userDao->getCustomerCampusesNameByCid($customerId);
    	return $result;
    }
    
/*
 * Validate if old password is right when one intents to modify password.
 */
    public function validateOldPassword($oldPassword,$customerId){
        
    	$customer = $this->userDao->getCustomerById($customerId);
    	
    	if($customer){
    	    if($customer[0]['password']==$oldPassword){
    	         return true;
            }else{
        	     return false;
            }
    	}else{
    		return false;
    	}
    }
    
/*
 * Update Customer Info
 */
    public function updateCustomer($param){
    	$this->userDao->updatePwd($param);
    }
    
    /*
     * get the campuses ambassador by campuses_id
     */
    public function getCustomerByCampusesId($campusesId){
    	return $this->userDao->getCustomerByCampusesId($campusesId);
    }
    
    /**
     * 兑换礼品减去相应的兑换积分
     */
    public function updateBuyerPointByCid($cid, $buyer_point){
    	$arr_map = array("points_buyer" => $buyer_point);
        return $this->userDao->update($arr_map, " id={$cid}"); 
    }    
    
    /**
     * 订单确认发邮件，判断用户类型：普通用户，大使，校园之星...
     */
    public function getUserCertfByUserId($userId){
        $result = $this->userDao->getUserById($userId);
        return $result;
    }    
    
    public function updateUserNumById($userNum, $userId){
    	$checkRst = $this->userDao->getByUserNum($userNum);
   		if(!empty($checkRst))
   			return false;
    	return $this->userDao->updateUserNumById($userNum, $userId);
    }
    
    
//    public function getTemplatePath(){ 	//get the template path from the DB
//    	$templatePath = TEMPLATEPATH;
//    	$param = array($templatePath);
//    	return $this->configDao->getByConfKey($param);
//    }

	/**
	 * update  customerInfo     email ,fullName,password 
	 * @author lijf
	 */
//    public function updateCustomerInformationById($email,$id,$name,$password = null){
//    	$newNameAndIdAndEmail = array($name,$email,$id);
//    	$this->userDao->updateInfomaiton($newNameAndIdAndEmail); //update email  ,fullName  
//    	if(isset($password)){
//    		$pwd=md5($password);
//    		$newPwdAndId = array($pwd,$id);
//    		$this->userDao->updatePwd($newPwdAndId);	//update  password
//    	}
//    }
//        
//    public function validatePwd($email,$pwd){
//    	$result = $this->userDao->getByEmailForPassword($email);
//    	if($pwd==$result[0]['password']){
//    		return true;   	//if pwd == oldpwd return true
//    	}
//    	return false;
//    }
}